package com.investment.advisor.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.investment.advisor.dto.ChatRequest;
import com.investment.advisor.dto.ChatResponse;
import com.investment.advisor.service.ChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChatServiceImpl implements ChatService {

    private static final Logger logger = LoggerFactory.getLogger(ChatServiceImpl.class);
    
    private static final String SYSTEM_PROMPT = "你是一位专业的智能投资顾问助手，名叫'投资小智'。你的主要职责是：\n" +
            "1. 解答用户关于投资组合、基金、策略等方面的问题\n" +
            "2. 提供专业的投资建议和风险提示\n" +
            "3. 解释系统功能和操作方法\n" +
            "4. 分析市场趋势和投资机会\n\n" +
            "在回答时，请注意：\n" +
            "1. 使用专业但易懂的语言\n" +
            "2. 始终强调风险控制的重要性\n" +
            "3. 给出具体的操作建议\n" +
            "4. 引导用户使用系统的各项功能\n" +
            "5. 对于不确定的信息，要明确告知用户\n\n" +
            "系统功能包括：\n" +
            "- 用户认证（注册、登录）\n" +
            "- 基金管理（查询、筛选、分析）\n" +
            "- 投资组合管理（创建、配置、调整）\n" +
            "- 策略管理（创建、因子配置）\n" +
            "- 交易管理（下单、查询、统计）\n" +
            "- 智能问答（投资咨询、操作指导）";

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public ChatServiceImpl() {
        // 配置RestTemplate的超时时间
        org.springframework.http.client.SimpleClientHttpRequestFactory factory = 
            new org.springframework.http.client.SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 连接超时5秒
        factory.setReadTimeout(30000);   // 读取超时30秒
        this.restTemplate = new RestTemplate(factory);
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public ChatResponse chat(ChatRequest request) {
        try {
            String requestId = generateRequestId();
            logger.info("Processing chat request [{}]: {}", requestId, request.getQuestion());

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 构建消息列表
            List<Map<String, String>> messages = new ArrayList<>();
            
            // 添加系统角色设定
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", SYSTEM_PROMPT);
            messages.add(systemMessage);

            // 添加用户问题
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", request.getQuestion());
            messages.add(userMessage);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", messages);
            requestBody.put("temperature", 0.7);
            requestBody.put("max_tokens", 1000); // 减少token数量以加快响应
            requestBody.put("stream", false);    // 禁用流式响应

            long startTime = System.currentTimeMillis();

            // 发送请求
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);

            long endTime = System.currentTimeMillis();
            logger.info("Request [{}] completed in {}ms", requestId, (endTime - startTime));

            // 解析响应
            JsonNode root = objectMapper.readTree(response.getBody());
            String answer = root.path("choices").get(0).path("message").path("content").asText();

            logger.info("Request [{}] response length: {} characters", requestId, answer.length());
            return new ChatResponse(answer);
        } catch (Exception e) {
            logger.error("Error processing chat request: {}", e.getMessage(), e);
            String errorMessage = e.getMessage();
            // 优化错误信息
            if (errorMessage.contains("Read timed out")) {
                return new ChatResponse(null, "服务响应超时，请稍后重试");
            } else if (errorMessage.contains("Connection timed out")) {
                return new ChatResponse(null, "无法连接到服务，请检查网络连接");
            }
            return new ChatResponse(null, "处理请求时发生错误，请稍后重试");
        }
    }

    private String generateRequestId() {
        return String.format("%d-%04d", System.currentTimeMillis(), (int)(Math.random() * 10000));
    }
} 